package com.liujiaqi.controller;

import com.liujiaqi.pojo.Emp;
import com.liujiaqi.pojo.Result;
import com.liujiaqi.service.EmpService;
import com.liujiaqi.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {

  @Autowired
  private EmpService empService;

  @PostMapping("/login")
  public Result login(@RequestBody Emp emp) {
    log.info("员工登录：{}", emp);

    Emp e = empService.login(emp);

    if(e != null) {
      // 登录成功，生成令牌，并下发令牌
      Map<String, Object> claims = new HashMap<>();
      claims.put("id", e.getId());
      claims.put("name", e.getName());
      claims.put("username", e.getUsername());
      String jwt = JwtUtils.generateJWT(claims);
      return Result.success(jwt);
    } else {
      // 登录失败返回错误信息
      return Result.error("用户名或密码错误");
    }
  }
}
